#pragma once
#include <filesystem>
#include <fstream>
#include <string>
#include "log.hpp"
#include "mutex.hpp"

using namespace LogModule;
using namespace LockModule;

namespace DataManagerModule
{
    std::string datapath = "./wwwroot/data.txt";
    class DataManager
    {
    public:
        void Write(std::string &message)
        {
            std::ofstream fout(datapath,std::ios::out | std::ios::in);
            if (!fout.is_open())
            {
                return;
            }
            LOG(INFO) << "data.txt open success:" << message;
            // 获取文件的当前大小
            _mutex.lock();
            fout.seekp(0, std::ios::end);
            std::streampos fileSize = fout.tellp();
            if (fileSize > 0)
            {
                // 将写入位置移到文件末尾的前一个字节
                fout.seekp(fileSize - (long int)1);
                LOG(INFO) << "data write:" << message;
                // 写入字符到倒数第二个位置
                fout << "," << message<<"]";
            }
            _mutex.unlock();
            fout.close();
        }
    private:
        Mutex _mutex;
    };
}